package com.zl.tcbnewcar.ui.fragment;


import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.TextView;

import com.zl.tcbnewcar.R;
import com.zl.tcbnewcar.base.BaseFragment;
import com.zl.tcbnewcar.base.RecyclerAdapter;
import com.zl.tcbnewcar.base.UniversalAdapter;
import com.zl.tcbnewcar.base.UniversalViewHolder;
import com.zl.tcbnewcar.base.ViewHolder;
import com.zl.tcbnewcar.model.CarUserEntity;
import com.zl.tcbnewcar.model.PersonGridBean;
import com.zl.tcbnewcar.ui.activity.CarCollectActivity;
import com.zl.tcbnewcar.ui.activity.CarHangCollectActivity;
import com.zl.tcbnewcar.ui.activity.CarHangDetailActivity;
import com.zl.tcbnewcar.ui.activity.CarShareListActivity;
import com.zl.tcbnewcar.ui.activity.FeedBackActivity;
import com.zl.tcbnewcar.ui.activity.LoginActivity;
import com.zl.tcbnewcar.ui.activity.MyCarActivity;
import com.zl.tcbnewcar.ui.activity.MyMotorsActivity;
import com.zl.tcbnewcar.ui.activity.MyServiceActivity;
import com.zl.tcbnewcar.ui.activity.MyUsedGoodsListActivity;
import com.zl.tcbnewcar.ui.activity.RealCarDealerActivity;
import com.zl.tcbnewcar.ui.activity.RealPersonActivity;
import com.zl.tcbnewcar.ui.activity.SendCarActivity;
import com.zl.tcbnewcar.ui.activity.SendServiceActivity;
import com.zl.tcbnewcar.ui.activity.SendUsedGoodsActivity;
import com.zl.tcbnewcar.ui.activity.SettingsActivity;
import com.zl.tcbnewcar.ui.activity.SubServiceActivity;
import com.zl.tcbnewcar.ui.activity.UpdatePasswordActivity;
import com.zl.tcbnewcar.ui.activity.WebActivity;
import com.zl.tcbnewcar.utils.API;
import com.zl.tcbnewcar.utils.HttpUtils;
import com.zl.tcbnewcar.utils.ImageLoader;
import com.zl.tcbnewcar.utils.SpUtlis;
import com.zl.tcbnewcar.utils.SystemUtils;
import com.zl.tcbnewcar.view.ImageTagView;
import com.zl.tcbnewcar.view.MyGridView;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import okhttp3.Request;

/**
 * @author zhanglei
 * @date 18/2/22
 */
public class PersonFragment extends BaseFragment {

    @BindView(R.id.iv_setting)
    ImageView ivSetting;
    @BindView(R.id.iv_person_icon)
    ImageView ivPersonIcon;
    @BindView(R.id.tv_person_name)
    TextView tvPersonName;
    @BindView(R.id.person_listView)
    RecyclerView personListView;
    Unbinder unbinder;
    @BindView(R.id.tagView_person)
    ImageTagView tagViewPerson;
    private RecyclerAdapter<PersonGridBean> mAdapter;
    private List<PersonGridBean> mList = new ArrayList<>();
    private String[] cars = {"发布车源", "我的车源", "赚取佣金", "车辆收藏"};
    private String[] carHangs = {"车行关注", "我的车行"};
    //    private String[] womens = {"客服电话", "免责声明", "意见反馈", "关于我们"};
    private String[] centers = {"用户信息", "密码修改", "实名认证", "车行认证", "中介认证", "客服电话", "免责声明", "意见反馈"};
    private String[] services = {"发布服务", "我的服务", "服务关注"};
    //    private String[] useds = {"二手商品发布", "我的二手商品", "二手商品收藏"};
    private String[] useds = {"二手商品发布", "我的二手商品"};


    private Integer[] iconCars = {R.mipmap.fbcy, R.mipmap.wdcy, R.mipmap.zjcl, R.mipmap.wdsc};
    private Integer[] iconCarhangs = {R.mipmap.wdgz, R.mipmap.wdch};
    //    private Integer[] iconWoMens = {R.mipmap.kfdh, R.mipmap.mzsm, R.mipmap.yjfk, R.mipmap.gy};
    private Integer[] iconCenters = {R.mipmap.ic_person_man, R.mipmap.ic_update_password, R.mipmap.ic_person_ren_zheng,
            R.mipmap.ic_ren_zheng, R.mipmap.zj, R.mipmap.kfdh, R.mipmap.mzsm, R.mipmap.yjfk};
    private Integer[] iconServices = {R.mipmap.ic_send_service, R.mipmap.ic_my_service, R.mipmap.ic_subscribe};
    //    private Integer[] iconUsed = {R.mipmap.icon_used, R.mipmap.icon_used_goods, R.mipmap.icon_used_guan_zhu};
    private Integer[] iconUsed = {R.mipmap.icon_used, R.mipmap.icon_used_goods};

    public PersonFragment() {
        // Required empty public constructor
    }

    public static PersonFragment newInstance() {

        Bundle args = new Bundle();

        PersonFragment fragment = new PersonFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_person, container, false);
        unbinder = ButterKnife.bind(this, view);
        initView();
        initData();
        initListener();
        return view;
    }

    private void initListener() {

    }

    private void initData() {

        /**
         * 在这每一个实体类就是一栏功能菜单，为了实现两个功能菜单的合并，添加了isShowTitle字段
         * 表示是否显示菜单的表头（默认是显示），当不显示时就先实现了菜单的合并
         * 这样做是为了实现每行显示的菜单数量不一致的情况，如服务中心菜单里第一行显示3个，第二行显示2个。
         */

        PersonGridBean carBean = new PersonGridBean();
        carBean.setTitle("车辆中心");
        List<PersonGridBean.ImageList> carList = new ArrayList<>();
        for (int i = 0; i < cars.length; i++) {
            PersonGridBean.ImageList bean = new PersonGridBean.ImageList();
            bean.setName(cars[i]);
            bean.setImagePath(iconCars[i]);
            carList.add(bean);
        }
        carBean.setImageList(carList);

        PersonGridBean serviceBean = new PersonGridBean();
        serviceBean.setTitle("服务中心");
        List<PersonGridBean.ImageList> serviceList = new ArrayList<>();
        for (int i = 0; i < services.length; i++) {
            PersonGridBean.ImageList bean = new PersonGridBean.ImageList();
            bean.setName(services[i]);
            bean.setImagePath(iconServices[i]);
            serviceList.add(bean);
        }
        serviceBean.setImageList(serviceList);

        PersonGridBean usedBean = new PersonGridBean();
        usedBean.setTitle("二手服务");
        usedBean.setShowTitle(false);
        List<PersonGridBean.ImageList> usedList = new ArrayList<>();
        for (int i = 0; i < useds.length; i++) {
            PersonGridBean.ImageList bean = new PersonGridBean.ImageList();
            bean.setName(useds[i]);
            bean.setImagePath(iconUsed[i]);
            usedList.add(bean);
        }
        usedBean.setImageList(usedList);

        PersonGridBean carHangBean = new PersonGridBean();
        carHangBean.setTitle("关于车行");
        carHangBean.setShowTitle(false);
        List<PersonGridBean.ImageList> carHangList = new ArrayList<>();
        for (int i = 0; i < carHangs.length; i++) {
            PersonGridBean.ImageList bean = new PersonGridBean.ImageList();
            bean.setName(carHangs[i]);
            bean.setImagePath(iconCarhangs[i]);
            carHangList.add(bean);
        }
        carHangBean.setImageList(carHangList);


        PersonGridBean centerBean = new PersonGridBean();
        centerBean.setTitle("个人中心");
        List<PersonGridBean.ImageList> centerList = new ArrayList<>();
        for (int i = 0; i < centers.length; i++) {
            PersonGridBean.ImageList bean = new PersonGridBean.ImageList();
            bean.setName(centers[i]);
            bean.setImagePath(iconCenters[i]);
            centerList.add(bean);
        }
        centerBean.setImageList(centerList);

//        PersonGridBean carWoMenBean = new PersonGridBean();
//        carWoMenBean.setTitle("关于我们");
//        List<PersonGridBean.ImageList> carWoMenList = new ArrayList<>();
//        for (int i = 0; i < womens.length; i++) {
//            PersonGridBean.ImageList bean = new PersonGridBean.ImageList();
//            bean.setName(womens[i]);
//            bean.setImagePath(iconWoMens[i]);
//            carWoMenList.add(bean);
//        }
//        carWoMenBean.setImageList(carWoMenList);

        mList.add(carBean);
        mList.add(carHangBean);
        mList.add(serviceBean);
        mList.add(usedBean);
        mList.add(centerBean);
//        mList.add(carWoMenBean);

        mAdapter.notifyDataSetChanged();
    }

    private void initView() {
        mAdapter = new RecyclerAdapter<PersonGridBean>(mActivity, mList, R.layout.person_list_item) {

            @Override
            protected void convert(ViewHolder holder, PersonGridBean s, int position) {
                holder.setText(R.id.tv_grid_title, s.getTitle());
                TextView view = holder.getView(R.id.tv_grid_title);
                if (s.isShowTitle()) {
                    view.setVisibility(View.VISIBLE);
                    view.setText(s.getTitle());
                } else {
                    view.setVisibility(View.GONE);
                }
                MyGridView grid = holder.getView(R.id.person_item_grid);
                final List<PersonGridBean.ImageList> imageList = s.getImageList();
                UniversalAdapter<PersonGridBean.ImageList> adapter = new UniversalAdapter<PersonGridBean.ImageList>(mActivity,
                        imageList, R.layout.person_grid_item) {
                    @Override
                    public void convert(UniversalViewHolder holder, int position, PersonGridBean.ImageList imageBean) {
                        holder.setText(R.id.tv_name, imageBean.getName());
                        holder.setImageResource(R.id.image_icon, imageBean.getImagePath());
                    }
                };
                grid.setAdapter(adapter);
                grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                        switch (imageList.get(i).getName()) {
                            case "发布车源":
                                SystemUtils.toActivity(mActivity, new Intent(mActivity, SendCarActivity.class));
                                break;
                            case "我的车源":
                                SystemUtils.toActivity(mActivity, new Intent(mActivity, MyCarActivity.class));
                                break;
                            case "我的车行":
                                intoMyMotors();
                                break;
                            case "车行关注":
                                SystemUtils.toActivityForResult(mActivity, new Intent(mActivity, CarHangCollectActivity.class), 0);
                                break;
                            //车辆收藏
                            case "车辆收藏":
                                SystemUtils.toActivityForResult(mActivity, new Intent(mActivity, CarCollectActivity.class), 1);
                                break;
                            //赚取佣金
                            case "赚取佣金":
                                SystemUtils.toActivityForResult(mActivity, new Intent(mActivity, CarShareListActivity.class), 1);
                                break;
                            //中介认证
                            case "中介认证":
                                applyInfo();
                                break;
                            //客服电话
                            case "客服电话":
                                callPhone();
                                break;
                            //免责声明
                            case "免责声明":
                                Intent intent = new Intent(mActivity, WebActivity.class);
                                intent.putExtra("url", "file:///android_asset/mian_ze.html");
                                intent.putExtra("title", "免责声明");
                                startActivity(intent);
                                break;
                            //意见反馈
                            case "意见反馈":
                                SystemUtils.toActivity(mActivity, new Intent(mActivity, FeedBackActivity.class));
                                break;
                            //关于我们
                            case "关于我们":
                                Intent intent1 = new Intent(mActivity, WebActivity.class);
                                intent1.putExtra("url", API.GYWM_URL);
                                intent1.putExtra("title", "关于我们");
                                startActivity(intent1);
                                break;
                            case "用户信息":
                                SystemUtils.toActivity(mActivity, new Intent(mActivity, SettingsActivity.class));
                                break;
                            case "密码修改":
                                SystemUtils.toActivity(mActivity, new Intent(mActivity, UpdatePasswordActivity.class));
                                break;
                            case "实名认证":
                                SystemUtils.toActivity(mActivity, new Intent(mActivity, RealPersonActivity.class));
                                break;
                            case "车行认证":
                                if (!SpUtlis.getLoginData(mActivity).isLogin()) {
                                    mActivity.startActivity(new Intent(mActivity, LoginActivity.class));
                                    return;
                                }
                                if (SpUtlis.getUserData(mActivity).getCarDealerId() != -1) {
                                    SystemUtils.toActivity(mActivity, new Intent(mActivity, RealCarDealerActivity.class));
                                } else {
                                    showToast("你还没有车行，请先上传车行信息");
                                }
                                break;
                            case "发布服务":
                                SystemUtils.toActivity(mActivity, new Intent(mActivity, SendServiceActivity.class));
                                break;
                            case "我的服务":
                                SystemUtils.toActivity(mActivity, new Intent(mActivity, MyServiceActivity.class));
                                break;
                            case "服务关注":
                                SystemUtils.toActivityForResult(mActivity, new Intent(mActivity, SubServiceActivity.class), 2);
                                break;
                            case "二手商品发布":
                                SystemUtils.toActivity(mActivity, new Intent(mActivity, SendUsedGoodsActivity.class));
                                break;
                            case "我的二手商品":
                                SystemUtils.toActivity(mActivity, new Intent(mActivity, MyUsedGoodsListActivity.class));
                                break;
                            case "二手商品收藏":
                                //TODO 此界面还未搭建
                                SystemUtils.toActivityForResult(mActivity, new Intent(mActivity, SubServiceActivity.class), 2);
                                break;
                        }
                    }
                });
            }
        };
        personListView.setLayoutManager(new LinearLayoutManager(mActivity, LinearLayoutManager.VERTICAL, false));
        personListView.setAdapter(mAdapter);
    }

    private void callPhone() {
        HttpUtils.getInstance().GET(mActivity, API.customerServicePhone, new HttpUtils.OnOkHttpCallback() {
            @Override
            public void onSuccess(String body) {
                try {
                    if (TextUtils.isEmpty(body)) {
                        showToast("手机号获取失败");
                        return;
                    }
                    JSONObject object = new JSONObject(body);
                    SystemUtils.call(mActivity, object.optString("data"));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Request error, Exception e) {

            }
        });
    }

    /**
     * 申请中介
     */
    private void applyInfo() {

        if (!SpUtlis.getLoginData(mActivity).isLogin()) {
            startActivity(new Intent(mActivity, LoginActivity.class));
            return;
        }

        CarUserEntity userData = SpUtlis.getUserData(mActivity);
        if (userData.getUserApply() == 1) {
            showToast("您已经进行了中介认证");
            return;
        }

        Map<String, String> params = new HashMap<>();
        params.put("uid", userData.getId() + "");
        HttpUtils.getInstance().Post(mActivity, params, API.applyInfo, new HttpUtils.OnOkHttpCallback() {
            @Override
            public void onSuccess(String body) {
                tagViewPerson.addImage(R.mipmap.zj);
            }

            @Override
            public void onError(Request error, Exception e) {

            }
        });
    }

    private void intoMyMotors() {

        if (!SpUtlis.getLoginData(mActivity).isLogin()) {
            mActivity.startActivity(new Intent(mActivity, LoginActivity.class));
            return;
        }

        Map<String, String> params = new HashMap<>();
        params.put("uid", SpUtlis.getUserData(mActivity).getId() + "");
        //在这里获取一下用户实名信息，如果有就可已进入我的车行
        HttpUtils.getInstance().Post(mActivity, params, API.getApproverInfo, new HttpUtils.OnOkHttpCallback() {
            @Override
            public void onSuccess(String body) {
                Integer carDealerId = SpUtlis.getUserData(mActivity).getCarDealerId();
                if (carDealerId == -1) { //没有车行去创建
                    SystemUtils.toActivity(mActivity, new Intent(mActivity, MyMotorsActivity.class));
                } else {//有车行去查看
                    Intent intent = new Intent(mActivity, CarHangDetailActivity.class);
                    intent.putExtra("did", carDealerId);
                    intent.putExtra("isMy", true);
                    SystemUtils.toActivity(mActivity, intent);
                }

            }

            @Override
            public void onError(Request error, Exception e) {

            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        updatePerson();
    }

    private void updatePerson() {
        boolean login = SpUtlis.getLoginData(mActivity).isLogin();
        if (login) {
            CarUserEntity userData = SpUtlis.getUserData(mActivity);
            tvPersonName.setText(userData.getUserNikeName());
            if (!TextUtils.isEmpty(userData.getUserImg())) {
                ImageLoader.loadRoundImageUrl(mActivity, userData.getUserImg(), ivPersonIcon);
            }
            List<Integer> list = new ArrayList<>();
            if (userData.getUserInter() != 0) {
                list.add(R.mipmap.ic_person_ren_zheng);
            }
            if (userData.getUserApply() == 1) {
                list.add(R.mipmap.zj);
            }
            if (userData.getCarDealerId() != 0 && userData.getUserDealerApply() != 0) {
                list.add(R.mipmap.ic_ren_zheng);
            }
            tagViewPerson.addImage(list);

        } else {
            tvPersonName.setText("点击登录");
            ivPersonIcon.setImageResource(R.mipmap.icon_touxiang);
            tagViewPerson.removeAllViews();
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick({R.id.iv_setting, R.id.arl_person_top, R.id.tv_sign_out})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            //进入设置
            case R.id.iv_setting:
                SystemUtils.toActivity(mActivity, new Intent(mActivity, SettingsActivity.class));
                break;
            //点击头像（若是未登录状态则进入登录页）
            case R.id.arl_person_top:
                login();
                break;
            //退出登录
            case R.id.tv_sign_out:
                startActivity(new Intent(mActivity, LoginActivity.class));
                break;
        }
    }

    private void login() {

        if (SpUtlis.getLoginData(mActivity).isLogin()) {
            return;
        }

        Intent intent = new Intent(mActivity, LoginActivity.class);
        intent.putExtra(API.ISFINISH, false);
        startActivity(intent);
    }
}
